package GUILag;

import ControllerLag.WorkingPlanCTR;
import ModelLag.Employee;
import java.text.DateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.swing.JOptionPane;

/**
 * Denne klasse bruges for at oprette en vagt på vagtplanen ud fra en dato.
 * @author DM75 Gruppe 3.
 * @version 22-12-2011.
 */
public class CreateShiftGUI extends javax.swing.JFrame {
    private Date dateInTable;
    private String weekDay;
    private WorkingPlanCTR WPCTR;
    private WPPanel WPRP;
    /** Creates new form CreateShiftGUI */
    public CreateShiftGUI() {
        initComponents();
    }
    
    public CreateShiftGUI(WPPanel WPRP) {
        initComponents();
        WPCTR = new WorkingPlanCTR();
        this.WPRP = WPRP;
        this.dateInTable = WPRP.getDateInTable();
        this.weekDay = WPRP.getWeekDay();
        // For at lave datoformatet om til dd-mm-åååå istedet for dd.mm.yyyy.
        DateFormat dF = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);
        String date = dF.format(dateInTable).replace('.', '-');
        dateLabel.setText(date);
        weekDayLabel.setText(weekDay);
        empComboBox.addItem("<Vælg Medarbejder>");
    }
    
    /**
     * Tjekker input i de 2 felter.
     */
    private void checkInput()
    {
        if(startFormattedTextField.getText().length() > 4 && endFormattedTextField.getText().length() > 4)
        {
            empComboBox.removeAllItems();
            empComboBox.addItem("<Vælg Medarbejder>");
            GregorianCalendar date = new GregorianCalendar();
            date.setTime(dateInTable);
            for(Employee employeeObj : WPCTR.getEmployeesAvailableForThisShift(date, startFormattedTextField.getText(), endFormattedTextField.getText()))
            {
                empComboBox.addItem(employeeObj);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        weekDayLabel = new javax.swing.JLabel();
        dateLabel = new javax.swing.JLabel();
        startLabel = new javax.swing.JLabel();
        startFormattedTextField = new javax.swing.JFormattedTextField();
        endLabel = new javax.swing.JLabel();
        endFormattedTextField = new javax.swing.JFormattedTextField();
        empComboBox = new javax.swing.JComboBox();
        employeeLabel = new javax.swing.JLabel();
        formatLabel = new javax.swing.JLabel();
        formatLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        annullerButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Opret ny vagt");
        setAlwaysOnTop(true);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
                formWindowLostFocus(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        weekDayLabel.setText("Ugedag");

        dateLabel.setText("Dato");

        startLabel.setText("Start:");

        startFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT))));
        startFormattedTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startFormattedTextFieldActionPerformed(evt);
            }
        });
        startFormattedTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                startFormattedTextFieldKeyReleased(evt);
            }
        });

        endLabel.setText("Slut:");

        endFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT))));
        endFormattedTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endFormattedTextFieldActionPerformed(evt);
            }
        });
        endFormattedTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                endFormattedTextFieldKeyReleased(evt);
            }
        });

        empComboBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                empComboBoxMouseClicked(evt);
            }
        });
        empComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                empComboBoxActionPerformed(evt);
            }
        });

        employeeLabel.setText("Medarbejder:");

        formatLabel.setText("TT:MM");

        formatLabel2.setText("TT:MM");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(weekDayLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(startLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(startFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(endLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(endFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(employeeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(empComboBox, 0, 178, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(182, 182, 182)
                        .addComponent(formatLabel2)
                        .addGap(53, 53, 53)
                        .addComponent(formatLabel)))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {endFormattedTextField, startFormattedTextField});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(formatLabel)
                    .addComponent(formatLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateLabel)
                    .addComponent(startLabel)
                    .addComponent(endLabel)
                    .addComponent(endFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(employeeLabel)
                    .addComponent(empComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(weekDayLabel)
                    .addComponent(startFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        annullerButton.setText("Annuller");
        annullerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                annullerButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(okButton)
                .addGap(18, 18, 18)
                .addComponent(annullerButton)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(annullerButton)
                    .addComponent(okButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(215, 215, 215)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void empComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_empComboBoxActionPerformed

    }//GEN-LAST:event_empComboBoxActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        // Tjekker for om starttiden er før sluttiden.
        if(startFormattedTextField.getText().length() > 0 && endFormattedTextField.getText().length() > 0 && empComboBox.getSelectedIndex() != 0)
        {
            int startTimeMin = (Integer.parseInt(startFormattedTextField.getText().substring(0,2)))*60 + Integer.parseInt(startFormattedTextField.getText().substring(3,5));
            int endTimeMin = (Integer.parseInt(endFormattedTextField.getText().substring(0,2)))*60 + Integer.parseInt(endFormattedTextField.getText().substring(3,5));
            
            if(startTimeMin > endTimeMin)
            {
                JOptionPane.showMessageDialog(this, "Starttidspunkt skal være før Sluttidspunkt.\nEn vagt kan senest slutte 23:59.", "Tidsrum", JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                String location = WPRP.getLoc();
                GregorianCalendar date = new GregorianCalendar();
                date.setTime(dateInTable);
                Employee employeeObj = (Employee) empComboBox.getSelectedItem();
                String cprNo = employeeObj.getCprNo();
                int result = WPCTR.createShift(date, location, employeeObj.getCprNo(), startFormattedTextField.getText(), endFormattedTextField.getText());
                if(result == 1)
                {
                    double hours = WPCTR.getHoursFromStartToEnd(startFormattedTextField.getText(), endFormattedTextField.getText());

                    String name = employeeObj.getfName() + " " + employeeObj.getlName();
                    int selectedRow = WPRP.getSelectedRow();
                    Object[] data = {null, null, startFormattedTextField.getText(), endFormattedTextField.getText(), hours, name, cprNo};
                    WPRP.getModel().insertRow(selectedRow+1, data);
                    JOptionPane.showMessageDialog(this, "Vagt oprettet.", "Oprettelse lykkedes", JOptionPane.INFORMATION_MESSAGE);
                    WPRP.setWorkingPlanGUIEnabled();
                    this.dispose();
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Fejl.", "Fejl", JOptionPane.ERROR_MESSAGE);
                }
            }    
        }        
        else
        {
            JOptionPane.showMessageDialog(this, "Udfyld alle felter og vælg en medarbejder.", "Fejl - Udfyld alle felter", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_okButtonActionPerformed

    
    
    private void annullerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annullerButtonActionPerformed
        WPRP.setWorkingPlanGUIEnabled();
        this.dispose();     }//GEN-LAST:event_annullerButtonActionPerformed

    private void empComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_empComboBoxMouseClicked

    }//GEN-LAST:event_empComboBoxMouseClicked

    private void startFormattedTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startFormattedTextFieldActionPerformed

    }//GEN-LAST:event_startFormattedTextFieldActionPerformed

    private void endFormattedTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endFormattedTextFieldActionPerformed

    }//GEN-LAST:event_endFormattedTextFieldActionPerformed

    private void startFormattedTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_startFormattedTextFieldKeyReleased
        checkInput();
    }//GEN-LAST:event_startFormattedTextFieldKeyReleased

    private void endFormattedTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_endFormattedTextFieldKeyReleased
        checkInput();
    }//GEN-LAST:event_endFormattedTextFieldKeyReleased

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        WPRP.setWorkingPlanGUIEnabled();
    }//GEN-LAST:event_formWindowClosing

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        WPRP.setWorkingPlanGUIDisabled();
    }//GEN-LAST:event_formWindowOpened

    private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus

    }//GEN-LAST:event_formWindowLostFocus

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CreateShiftGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CreateShiftGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CreateShiftGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CreateShiftGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CreateShiftGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton annullerButton;
    private javax.swing.JLabel dateLabel;
    private javax.swing.JComboBox empComboBox;
    private javax.swing.JLabel employeeLabel;
    private javax.swing.JFormattedTextField endFormattedTextField;
    private javax.swing.JLabel endLabel;
    private javax.swing.JLabel formatLabel;
    private javax.swing.JLabel formatLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton okButton;
    private javax.swing.JFormattedTextField startFormattedTextField;
    private javax.swing.JLabel startLabel;
    private javax.swing.JLabel weekDayLabel;
    // End of variables declaration//GEN-END:variables
}
